<template>
  <div class="registerForm">
    <el-form
      ref="registerForm"
      :model="form"
      :rules="rules"
      status-icon
      class="form"
    >
      <el-form-item prop="username">
        <el-input
          placeholder="用户名/手机"
          v-model="form.username"
          @focus="clearValid('username')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="captcha">
        <el-input
          placeholder="验证码"
          v-model="form.captcha"
          @focus="clearValid('captcha')"
        >
          <template slot="append">
            <el-button @click="handleSendCaptcha">发送验证码</el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="nickname">
        <el-input
          placeholder="你的名字"
          v-model="form.nickname"
          @focus="clearValid('nickname')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="密码"
          v-model="form.password"
          @focus="clearValid('password')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="checkpass">
        <el-input
          placeholder="确认密码"
          v-model="form.checkpass"
          @focus="clearValid('checkpass')"
        ></el-input>
      </el-form-item>
      <el-button type="primary" @click="hangdlereg" class="regbtn"
        >注册</el-button
      >
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    // value表示输入的值，callback是回调函数
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        console.log(12);
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      form: {
        username: "",
        captcha: "",
        nickname: "",
        password: "",
        checkpass: "", // 再次验证密码
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入合法的用户名/手机号",
            trigger: "blur",
          },
        ],
        captcha: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
        nickname: [
          {
            required: true,
            message: "请输入昵称",
            trigger: "blur",
          },
        ],
        checkpass: [
          {
            validator: validatePass, // 调用函数验证密码
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 发送验证码
    handleSendCaptcha() {
      // 先进行错误排除，再发送请求拿到验证码

      // 没有输入手机号
      if (!this.form.username) {
        // 添加提示信息
        this.$confirm("手机号码不能为空", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning",
        });
        return; // 结束代码
      }
      // 手机好输入不是11位
      if (this.form.username.length !== 11) {
        this.$confirm("手机号码格式错误❌", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning",
        });
        return; // 结束代码
      }

      this.$axios({
        url: "captchas",
        method: "post",
        data: {
          tel: this.form.username,
        },
      }).then((res) => {
        console.log(res);
        const { code } = res.data;
        // this.$confirm(`模拟手机验证码为：${code}`, "提示", {
        //   confirmButtonText: "确定",
        //   showCancelButton: false,
        //   type: "warning",
        // });
        this.$message({
          message: `模拟手机验证码为：${code}`,
          type: "success",
          showClose: true,
          duration: 0,
        });
      });
    },
    // 请求注册
    hangdlereg() {
      // validate()对表单进行规则验证
      this.$refs["registerForm"].validate((valid) => {
        if (valid) {
          // 使用剩余参数法去除掉checkpass参数
          const { checkpass, ...props } = this.form;

          this.$store
            .dispatch("user/register", props)
            .then((res) => {
              // 成功提示
              this.$message.success("注册成功");
              setTimeout(() => {
                this.$router.push({ path: "/" });
              }, 1000);
            })
            .then(() => {
              // 自动切换到登录页
              this.$emit("goLogin");
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("注册失败");
            });

          // 发送注册请求
          // this.$axios({
          //   url: "/accounts/register",
          //   method: "post",
          //   data: props,
          // })
          //   .then((res) => {
          //     console.log(res.data); // 包含token、user对象
          //     this.$message.success("恭喜！注册成功");
          //   })
          //   .catch((err) => {
          //     this.$message.error("注册失败");
          //   });
        }
      });
    },
    // 清除当前验证
    clearValid(propname) {
      this.$refs.registerForm.clearValidate(propname);
    },
  },
};
</script>

<style lang="less" scoped>
.registerForm {
  padding: 25px;

  .regbtn {
    width: 100%;
    margin-top: 10px;
  }
}
</style>